package com.halden.mycache.support.saveStrategy.RDBSaveStrategy.impl;

import com.halden.mycache.support.saveStrategy.RDBSaveStrategy.IRDBSaveMode;
import com.halden.mycache.Utils.KryoUtil;
import com.halden.mycache.core.IMyCache;
import com.halden.mycache.core.Impl.CacheValue;
import java.io.*;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: halden
 * @Data:2023/2/7 10:10
 * @Description:
 */
public class RdbKryoSerializeSaveModeRdb<K,V> extends RdbAbstractSaveMode<K,V> implements IRDBSaveMode<K,V> {

    @Override
    public void save(IMyCache<K, V> myCache, String fileName) {
        String kryoString = getKryoString(myCache);
        saveString(kryoString,fileName);
    }

    @Override
    public Map<K, CacheValue<V>> readSave(File file, Map<K, CacheValue<V>> map) {
        String kryoString = readString(file);
        ConcurrentHashMap concurrentHashMap = (ConcurrentHashMap) KryoUtil.readFromString(kryoString);
        // 将对象进行转换添加进cache的map中
        for (Object entry : concurrentHashMap.entrySet()){
            CacheValue value = (CacheValue) ((Map.Entry) entry).getValue();
            K key = (K) (((Map.Entry) entry).getKey());
            map.put(key, value);
        }
        return map;
    }


    private String getKryoString(IMyCache<K, V> myCache){
        Map<K, CacheValue<V>> map = myCache.map();
        String s = KryoUtil.writeToString(map);
        return s;
    }
}
